package com.dynamic.mybatis.web.security;

import com.dynamic.mybatis.core.intercept.DynamicSqlSessionHandler;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.session.DynamicSqlSessionTemplate;
import com.dynamic.mybatis.core.toolkit.BeanUtils;
import com.dynamic.mybatis.core.toolkit.StringUtils;

import java.util.Map;
/**
　* @Description: 取缓存参数并合并到参数中
　*/
public class SecurityParameterHandler extends SecurityParameterInterceptHandler implements DynamicSqlSessionHandler {

    public SecurityParameterHandler(DynamicSqlSessionTemplate dynamicSqlSessionTemplate) {
        super(dynamicSqlSessionTemplate);
    }

    @Override
    public Object before(DynamicMappedStatement dms, Object p) {
        if(!(p instanceof SecurityParameter)){ return p ;}

        SecurityAuthorizationParameter parameter = (SecurityAuthorizationParameter) p;
        Object param = parameter.getParameter();
        if(StringUtils.isNotEmpty(parameter.getToken())){
            Object p1 =  getSecurityParameter(dms.getNamespace(),parameter.getToken());
            if(parameter != null && parameter instanceof Map &&p1 != null && p1 instanceof Map){
               param =   BeanUtils.copy(p1,parameter);
            }
        }
        return param;
    }



    @Override
    public Object after(DynamicMappedStatement dms, Object parameter, Object result) {
        return result;
    }
}
